package com.umgsai.springbootstudy.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.umgsai.springbootstudy.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

@Slf4j
@RestController
public class TestController {

    @Resource
    private TestService testService;

    @RequestMapping(value = "/test/async", method = RequestMethod.GET)
    public Object testAsync(){
        log.info("调用开始，{}", Thread.currentThread().getName());
        Map<String, Object> resultMap = Maps.newHashMap();
        testService.testAsync();
        resultMap.put("msg", "调用成功");
        log.info("调用结束，{}", Thread.currentThread().getName());
        return resultMap;
    }

    @RequestMapping(value = "/test/asyncReturn", method = RequestMethod.GET)
    public Object testAsyncReturn() throws Exception{
        log.info("调用开始，{}", Thread.currentThread().getName());
        Map<String, Object> resultMap = Maps.newHashMap();
        List<Future<String>> futureList = Lists.newArrayList();
        for (int i = 0; i < 10; i ++) {
            Future<String> future = testService.testAsync("Tom" + i);
            futureList.add(future);
        }
        resultMap.put("msg", "调用成功");
        log.info("调用结束，{}", Thread.currentThread().getName());

        List<String> resultList = Lists.newArrayList();
        for (Future future : futureList) {
            String string = (String) future.get();
            resultList.add(string);
        }
        log.info("主线程获取结果：{}", resultList);
        return resultMap;
    }
}
